package com.example.orderserver.service;

import com.example.orderserver.controller.vo.GoodsVO;
import com.example.orderserver.controller.vo.OrderVO;
import com.example.orderserver.dao.OrderDao;
import com.example.orderserver.dao.OrderItemDao;
import com.example.orderserver.enums.OrderStatusEnum;
import com.example.orderserver.feign.GoodsFeignClient;
import com.example.orderserver.utils.LeafUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class OrderService {

    @Autowired
    private OrderDao orderDao;

    @Autowired
    @Qualifier("goodsFeignClient")
    private GoodsFeignClient goodsFeignClient;

    @Autowired
    private OrderItemDao orderItemDao;

    @Transactional
    public String generatorOrder(OrderVO orderVO) {
        //1、生成订单汇总信息
        List<GoodsVO> goodsVOS = orderVO.getGoodsVOS();
        int totalPrice = goodsVOS.stream().mapToInt(GoodsVO::getPrice).sum();
        Long orderId = LeafUtil.getLeafId("order");
        orderDao.insertOrder(orderId, orderVO.getUserId(), OrderStatusEnum.NOT_PAY.getCode(), totalPrice);

        for (GoodsVO goodsVO : goodsVOS) {
            //2、根据订单中的商品详情去扣减商品的库存（远程调用）
            Boolean result = goodsFeignClient.deductGoodsStock(goodsVO.getGoodsId(), goodsVO.getQuantity());
            if (!result) {
                throw new RuntimeException("扣减库存失败");
            }
            //3、生成订单的明细数据
            orderItemDao.insertOrderItem(LeafUtil.getLeafId("order_item"), goodsVO.getGoodsId(),
                    orderId, goodsVO.getQuantity(), goodsVO.getPrice());
        }
        return "创建订单成功";
    }
}